{extend name="common/index" /}

{block name="title"}
<script type="text/html">
</script>

<title>{$title}</title>{/block}

{block name="action"}
<script type="text/html" id="barDemo">
    {if (!empty($edit_url))}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</a>
    {/if}
    {if (!empty($del_url))}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {/if}
    {if (!empty($sync_url))}
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="sync">同步配置</a>
    {/if}
    {{#  if(d.crm_url){ }}
     <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="inHouTai" data-url="{{d.crm_url}}/unAuthorizedLogin/{{d.crm_name}}/{{d.crm_pwd}}">进入后台</a>
    {{#  } }}
    {if (!empty($sync_sql_url))}
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="sync_sql">同步数据库</a>
    {/if}
    <a class="layui-btn layui-btn-xs" lay-event="check_single" style="background-color: #009688;">检测状态</a>
</script>

<!-- 添加顶部工具栏模板 -->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="batchCheckStatus" style="background-color: #009688;">
            <i class="layui-icon layui-icon-refresh"></i> 批量检测连接状态
        </button>
    </div>
</script>
{/block}
{block name="footer"}
<script type="text/javascript">

    //初始化参数
    var cols = init_cols({$cols|json_encode|raw});
    var list_url = '{$list_url}';
    var edit_url = '{$edit_url?:""}';
    var del_url = '{$del_url?:""}';
    var sync_url = '{$sync_url?:""}';
    var batch_check_status_url = '{$batch_check_status_url?:""}';
    
    //初始化表格字段
    function init_cols(cols){
        var arr = [];
        cols.forEach((val) => {
            if(val.type == 'button'){
                val.templet = function (d) {
                    var str = '';
                    d.LAY_COL.option.forEach((v) => {
                        if(v[0] == d[d.LAY_COL['field']]){
                            var color = 'layui-btn-primary';
                            if(v[2] == ''){
                                color = '';
                            }else if(v[2] != undefined){
                                color = 'layui-btn-'+v[2];
                            }
                            str = '<button type="button" class="layui-btn layui-btn-xs '+color+'">'+v[1]+'</button>';
                        }
                    })
                    return str;
                }
            }else if(val.type == 'img'){
                val.templet = function (d) {
                    var str = '';
                    d[d.LAY_COL['field']].split(',').forEach((elem, index) => {
                        if(elem != ''){
                            str += '<img style="padding-left: 10px;" src="'+elem+'" class="view_cp" width="auto" height="100%">';
                        }
                    });
                    return str;
                }
            // 删除第292-307行的错误代码，并在第66-74行之间修改为：
            }else if(['mysql_info', 'redis_info', 'mongo_info', 'url'].includes(val.field)){
            // 为包含HTML内容的字段添加可展开的模板函数
            val.templet = function (d) {
            var value = d[d.LAY_COL['field']];
            // 提取纯文本用于截断显示
            var tempDiv = document.createElement('div');
            tempDiv.innerHTML = value;
            var textContent = tempDiv.textContent || tempDiv.innerText || '';
            
            // 截断文本到合适长度
            var maxLength = 80; // 可根据需要调整
            var truncatedText = textContent.length > maxLength ? textContent.substring(0, maxLength) : textContent;
            
            return '<div class="expandable-cell" style="display: flex; align-items: center; min-height: 20px;">' +
                   '<div class="content" style="flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 20px;" data-full-content="' + value.replace(/"/g, '&quot;') + '">' +
                   (textContent.length > maxLength ? truncatedText + '...' : textContent) +
                   '</div>' +
                   '<span class="expand-btn" style="margin-left: 8px; color: #1890ff; cursor: pointer; flex-shrink: 0; font-size: 12px;" onclick="toggleExpand(this)">展开</span>' +
                   '</div>';
            }
            }
            arr.push(val);
        });
        return cols;
    }

    layui.config({
        base: '/vendor/layui-admin/layui/modules/js/' //静态资源所在路径
    });

    layui.define(['table','form','admin','laydate'], function(exports) {
        var $ = layui.$;
        var table = layui.table;
        var form = layui.form;
        var laydate = layui.laydate;
        var table_filter = {};
        
        table.render({
            elem: '#table'
            , url: list_url
            , cols: [cols]
            , page: true
            , limit: 20
            , height: 'full-180'
            , toolbar: '#toolbarDemo' // 使用自定义工具栏
            , text: {
                none: '无数据' //默认：无数据。
            }
            , even: true
            ,where: {
                filter:table_filter
            },
        });

        // 头工具栏事件
        table.on('toolbar(table)', function(obj){
            if(obj.event === 'batchCheckStatus'){
                layer.confirm('确认检测当前页面所有分区的连接状态？此操作可能需要一些时间。', {
                    title: '批量检测确认',
                    btn: ['开始检测', '取消']
                }, function(index){
                    // 显示加载层
                    var loadIndex = layer.load(2, {shade: [0.3, '#000']});
                    
                    $.ajax({
                        url: batch_check_status_url
                        ,type: 'POST'
                        ,timeout: 60000 // 1分钟超时
                        ,success: function(res){
                            layer.close(loadIndex);
                            console.log('Batch check response:', res);
                            
                            if (res.code == 0){
                                console.log('Calling updateTableWithStatus with:', res.data);
                                // 更新表格数据
                                updateTableWithStatus(res.data);
                                layer.msg('批量检测完成！', {icon: 1, time: 3000});
                            } else{
                                layer.alert('检测失败: ' + (res.msg || '未知错误'), {
                                    title: '检测失败',
                                    icon: 2
                                });
                            }
                        }
                        ,error: function(xhr, status, error){
                            layer.close(loadIndex);
                            var errorMsg = '检测请求失败';
                            if (status === 'timeout') {
                                errorMsg = '检测超时，请检查网络连接';
                            }
                            layer.alert(errorMsg, {
                                title: '请求失败',
                                icon: 2
                            });
                        }
                    });
                    layer.close(index);
                });
            }
        });

        //tool 事件监听
        table.on('tool(table)', function(obj){
            var data = obj.data;
            
            // 单个分区状态检测
            if(obj.event === 'check_single'){
                var loadIndex = layer.load(2, {shade: [0.3, '#000']});
                
                $.ajax({
                    url: '/backmanage/projectPartitionConfig/checkStatus'
                    ,data: {"partition_id": data.partition_id}
                    ,type: 'POST'
                    ,timeout: 30000 // 30秒超时
                    ,success: function(res){
                        layer.close(loadIndex);
                        if (res.code == 0){
                            // 更新当前行数据
                            updateSingleRowStatus(obj, res.data);
                            layer.msg('检测完成！', {icon: 1, time: 2000});
                        } else{
                            layer.msg('检测失败: ' + (res.msg || '未知错误'), {icon: 2});
                        }
                    }
                    ,error: function(xhr, status, error){
                        layer.close(loadIndex);
                        layer.msg('检测请求失败', {icon: 2});
                    }
                });
            }
            
            if(obj.event === 'edit'){
                layer.open({
                    type: 2,
                    shadeClose: true,
                    shade: false,
                    maxmin: true, //开启最大化最小化按钮
                    area: ["80%", "80%"],
                    content: edit_url+'?id='+data.id,
                    end: function () {
                        //更新表格
                        $("#layui-icon-refresh").click();
                    }
                });
            }
            
            // 进入后台事件处理
            if(obj.event === 'inHouTai'){
                // 构建动态URL
                var backendUrl = data.crm_url + '/unAuthorizedLogin/' + data.crm_name + '/' + data.crm_pwd;
                
                window.open(backendUrl, '_blank');
            }
            
            // 同步事件处理
            if(obj.event === 'sync'){
                layer.confirm('确认将此配置同步至平台？', function(index){
                    $.ajax({
                        url: sync_url
                        ,data: {"partition_id":data.partition_id}
                        ,type: 'POST'
                        ,success(res){
                            if (res.code == 0){
                                table.reload("table");
                                layer.msg('同步成功');
                            } else{
                                layer.msg('同步失败: ' + (res.msg || '未知错误'));
                            }
                        },
                        error: function(){
                            layer.msg('同步请求失败');
                        }
                    });
                    layer.close(index);
                });
            }
            
            // 删除事件处理
            if(obj.event === 'del'){
                layer.confirm('真的删除行嘛，删除后该分区下的主播数据会统一注销', function(index){
                    $.ajax({
                        url: del_url
                        ,data: {"partition_id":data.partition_id}
                        ,type: 'DELETE'
                        ,success(res){
                            if (res.code == 0){
                                table.reload("table");
                                layer.msg('删除成功');
                            } else{
                                layer.msg('删除失败: ' + (res.msg || '未知错误'));
                            }
                        },
                        error: function(){
                            layer.msg('删除请求失败');
                        }
                    });
                    layer.close(index);
                });
            }
            
            // 同步数据库事件处理
            if(obj.event === 'sync_sql'){
                layer.confirm('确认同步数据库？此操作将根据SQL文件创建数据库和表结构。', {
                    title: '同步数据库确认',
                    btn: ['确认同步', '取消']
                }, function(index){
                    // 显示加载层
                    var loadIndex = layer.load(2, {shade: [0.3, '#000']});
                    
                    $.ajax({
                        url: '/backmanage/projectPartitionConfig/syncSql'
                        ,data: {"partition_id": data.partition_id}
                        ,type: 'POST'
                        ,timeout: 300000 // 5分钟超时
                        ,success: function(res){
                            layer.close(loadIndex);
                            if (res.code == 0){
                                layer.msg('数据库同步成功！', {icon: 1, time: 3000});
                            } else{
                                layer.alert('同步失败: ' + (res.msg || '未知错误'), {
                                    title: '同步失败',
                                    icon: 2
                                });
                            }
                        }
                        ,error: function(xhr, status, error){
                            layer.close(loadIndex);
                            var errorMsg = '同步请求失败';
                            if (status === 'timeout') {
                                errorMsg = '同步超时，请检查网络连接或联系管理员';
                            } else if (xhr.responseJSON && xhr.responseJSON.msg) {
                                errorMsg = xhr.responseJSON.msg;
                            }
                            layer.alert(errorMsg, {
                                title: '请求失败',
                                icon: 2
                            });
                        }
                    });
                    layer.close(index);
                });
            }
        });

        //筛选框监听
        form.on('submit(search)', function(data){
            table_filter = data.field;
            reload();
            return false;
        });
        
        //重载 刷新
        $('#layui-icon-refresh').click(function () {
            reload();
        });
        
        //重载 刷新
        function reload(){
            table.reload('table',{
                where: {
                    filter:table_filter
                }
            });
        }
        
        exports('level', {});

        $(document).on('click','.view_cp',function(){
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                area: 'auto',
                content: '<img style="height:500px;" src="'+$(this).attr('src')+'">'
            });
        });

        // 在页面底部添加样式和函数
        $(document).ready(function() {
            // 添加样式
            $('<style>').text(`
                .expandable-cell {
                    position: relative;
                    max-width: 200px;
                    display: flex;
                    align-items: flex-start;
                }
                .expand-btn {
                    cursor: pointer;
                    color: #1890ff;
                    font-weight: bold;
                    margin-left: 5px;
                    user-select: none;
                    flex-shrink: 0;
                    margin-top: 2px;
                }
                .cell-content {
                    flex: 1;
                }
                .cell-content.collapsed {
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    height: 20px;
                    line-height: 20px;
                }
                .cell-content.expanded {
                    white-space: normal;
                    word-wrap: break-word;
                    line-height: 1.4;
                }
            `).appendTo('head');
        });

        // 批量检测后更新表格数据
        function updateTableWithStatus(statusData) {
            console.log('updateTableWithStatus called with data:', statusData);
            console.log('statusData type:', typeof statusData);
            console.log('statusData is array:', Array.isArray(statusData));
            
            // 打印每个元素的详细信息
            if (Array.isArray(statusData)) {
                statusData.forEach(function(item, index) {
                    console.log('Item', index, ':', item);
                    console.log('Item keys:', Object.keys(item));
                });
            }
            
            // 检查数据格式，如果是对象则转换为数组
            var dataArray = [];
            if (Array.isArray(statusData)) {
                // 如果已经是数组，检查是否包含partition_id
                statusData.forEach(function(item, index) {
                    if (item.partition_id === undefined) {
                        // 如果没有partition_id，尝试从索引或其他字段获取
                        console.log('Missing partition_id for item:', item);
                        // 可能需要从表格的顺序来推断partition_id
                        item.partition_id = index; // 临时使用索引作为partition_id
                    }
                    dataArray.push(item);
                });
            } else if (typeof statusData === 'object') {
                // 将对象转换为数组，键作为partition_id
                for (var partitionId in statusData) {
                    if (statusData.hasOwnProperty(partitionId)) {
                        var item = statusData[partitionId];
                        item.partition_id = partitionId;
                        dataArray.push(item);
                    }
                }
            } else {
                console.error('statusData format is invalid:', statusData);
                return;
            }
            
            console.log('Converted data array:', dataArray);
            
            // 遍历状态数据，更新对应的表格行显示
            dataArray.forEach(function(status) {
                console.log('Processing status for partition:', status.partition_id, status);
                
                // 查找对应的表格行
                var found = false;
                $('tbody tr').each(function(rowIndex) {
                    var $tr = $(this);
                    var partitionIdCell = $tr.find('td[data-field="partition_id"]');
                    var partitionId = partitionIdCell.text().trim();
                    
                    console.log('Row', rowIndex, 'partition_id:', partitionId, 'against:', status.partition_id);
                    
                    // 尝试多种匹配方式
                    if (partitionId == status.partition_id || rowIndex == status.partition_id) {
                        found = true;
                        console.log('Found matching row for partition:', status.partition_id, 'at row index:', rowIndex);
                        
                        // 更新MySQL状态列
                        if (status.mysql_status !== undefined) {
                            var mysqlCell = $tr.find('td[data-field="mysql_status"]');
                            var mysqlButton = getStatusButton(status.mysql_status, 'MySQL');
                            console.log('Updating MySQL status to:', status.mysql_status, 'Button HTML:', mysqlButton);
                            mysqlCell.find('.layui-table-cell').html(mysqlButton);
                        }
                        
                        // 更新Redis状态列
                        if (status.redis_status !== undefined) {
                            var redisCell = $tr.find('td[data-field="redis_status"]');
                            var redisButton = getStatusButton(status.redis_status, 'Redis');
                            console.log('Updating Redis status to:', status.redis_status, 'Button HTML:', redisButton);
                            redisCell.find('.layui-table-cell').html(redisButton);
                        }
                        
                        // 更新MongoDB状态列
                        if (status.mongo_status !== undefined) {
                            var mongoCell = $tr.find('td[data-field="mongo_status"]');
                            var mongoButton = getStatusButton(status.mongo_status, 'Mongo');
                            console.log('Updating MongoDB status to:', status.mongo_status, 'Button HTML:', mongoButton);
                            mongoCell.find('.layui-table-cell').html(mongoButton);
                        }
                    }
                });
                
                if (!found) {
                    console.warn('No matching row found for partition_id:', status.partition_id);
                }
            });
        }

        // 单个检测后更新行数据
        function updateSingleRowStatus(obj, statusData) {
            var $tr = $(obj.tr);
            
            // 更新MySQL状态
            if (statusData.mysql_status !== undefined) {
                var mysqlCell = $tr.find('td[data-field="mysql_status"]');
                var mysqlButton = getStatusButton(statusData.mysql_status, 'MySQL');
                mysqlCell.find('.layui-table-cell').html(mysqlButton);
            }
            
            // 更新Redis状态
            if (statusData.redis_status !== undefined) {
                var redisCell = $tr.find('td[data-field="redis_status"]');
                var redisButton = getStatusButton(statusData.redis_status, 'Redis');
                redisCell.find('.layui-table-cell').html(redisButton);
            }
            
            // 更新MongoDB状态
            if (statusData.mongo_status !== undefined) {
                var mongoCell = $tr.find('td[data-field="mongo_status"]');
                var mongoButton = getStatusButton(statusData.mongo_status, 'Mongo');
                mongoCell.find('.layui-table-cell').html(mongoButton);
            }
        }

        // 根据状态生成按钮HTML
        function getStatusButton(status, type) {
            var buttonClass = '';
            var buttonText = '';
            
            switch(status) {
                case 1:
                    buttonClass = 'layui-btn-normal';
                    buttonText = '已连接';
                    break;
                case 0:
                    buttonClass = 'layui-btn-danger';
                    buttonText = '连接失败';
                    break;
                default:
                    buttonClass = 'layui-btn-warm';
                    buttonText = '未检测';
                    break;
            }
            
            return '<button type="button" class="layui-btn layui-btn-xs ' + buttonClass + '">' + buttonText + '</button>';
        }

        // 将函数暴露到全局作用域，以便在事件处理中调用
        window.updateTableWithStatus = updateTableWithStatus;
        window.updateSingleRowStatus = updateSingleRowStatus;

    });




// 添加切换展开/收起的函数
function toggleExpand(btn) {
    var cell = btn.closest('.expandable-cell');
    var content = cell.querySelector('.content');
    var fullContent = content.getAttribute('data-full-content');
    var isExpanded = btn.textContent === '收起';
    
    if (isExpanded) {
        // 收起：重新截断显示
        var tempDiv = document.createElement('div');
        tempDiv.innerHTML = fullContent;
        var textContent = tempDiv.textContent || tempDiv.innerText || '';
        var maxLength = 50;
        var truncatedText = textContent.substring(0, maxLength);
        
        content.style.whiteSpace = 'nowrap';
        content.style.overflow = 'hidden';
        content.style.textOverflow = 'ellipsis';
        content.textContent = truncatedText + '...';
        btn.textContent = '展开';
    } else {
        // 展开：显示完整HTML内容
        content.style.whiteSpace = 'normal';
        content.style.overflow = 'visible';
        content.style.textOverflow = 'initial';
        content.innerHTML = fullContent;
        btn.textContent = '收起';
    }
}
</script>
{/block}
